package net.chasing.androidbaseconfig.util;

import android.graphics.Paint;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class StringUtils {
    public static String compressToString(String str) {
        return byteArrayToString(compress(str, "GBK"));
    }

    public static String uncompressByString(String str) {
        return uncompress(stringToByteArray(str), "GBK");
    }

    private static byte[] compress(String str, String encoding) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(encoding));
            gzip.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    private static String uncompress(byte[] str, String encoding) {
        if (str == null || str.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in;
        try {
            in = new ByteArrayInputStream(str);
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            return out.toString(encoding);
        } catch (UnsupportedEncodingException e) {
            return out.toString();
        }
    }

    // 将字节数组转换为字符串
    public static String byteArrayToString(byte[] byteArray) {
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

    // 将字符串转换为字节数组
    public static byte[] stringToByteArray(String str) {
        return Base64.decode(str, Base64.DEFAULT);
    }

    /**
     * 文本截取追加省略号
     */
    public static Object[] ellipse(String content, float maxWidth, Paint paint) {
        Object[] res = new Object[2];
        String cur = content + "...";
        float width = paint.measureText(cur);
        while (width > maxWidth) {
            content = subStringDealEmoji(content, 0, content.length() - 1, 2, false);
            cur = content + "...";
            width = paint.measureText(cur);
        }
        res[0] = cur;
        res[1] = width;
        return res;
    }

    /**
     * 字符串是否以emoji表情字符结尾
     */
    public static boolean isEmoji(char c) {
        int type = Character.getType(c);
        return type == Character.SURROGATE || type == Character.OTHER_SYMBOL;
    }

    public static boolean isNumber(char c) {
        return c >= 48 && c <= 57;
    }

    /**
     * 字符串截取，避免emoji表情符号中间截断的情况
     *
     * @param orientation 方向  0 左右都进行  1 左边进行  2 右边进行
     * @param isAdd       是否是增加字符
     */
    public static String subStringDealEmoji(String str, int start, int end, int orientation, boolean isAdd) {
        int actStart = start, actEnd = end;

        if (orientation == 0 || orientation == 1) {
            int type = Character.getType(str.charAt(start));
            boolean isEndWithEmoji = type == Character.SURROGATE || type == Character.OTHER_SYMBOL;
            if (isEndWithEmoji)
                actStart = isAdd ? start + 1 : start - 1;
        }
        if (orientation == 0 || orientation == 2) {
            int type = Character.getType(str.charAt(end));
            boolean isEndWithEmoji = type == Character.SURROGATE || type == Character.OTHER_SYMBOL;
            if (isEndWithEmoji)
                actEnd = isAdd ? end + 1 : end - 1;
        }
        if (actEnd >= str.length())
            actEnd = str.length();
        if (actStart < 0)
            actStart = 0;
        if (actStart >= actEnd)
            return "";
        else
            return str.substring(actStart, actEnd);
    }

    /**
     * 获取一行文本
     *
     * @param content 需要截取的文本
     * @param maxWidth 限制一行的最大宽度
     * @param paint 画笔，包含了字体大小等
     * @param ellipse 超出长度时，是否使用省略号
     */
    public static Object[] getLine(String content, float maxWidth, Paint paint, boolean ellipse) {
        Object[] res = new Object[2];
        int index = StringUtils.isEmoji(content.charAt(0)) ? 2 : 1;
        String actContent = content.substring(0, index);
        float contentWidth = paint.measureText(actContent);

        while (contentWidth < maxWidth && index < content.length()) {
            if (StringUtils.isEmoji(content.charAt(index)))
                ++index;
            actContent = content.substring(0, ++index);
            contentWidth = paint.measureText(actContent);
        }

        if (contentWidth > maxWidth) {
            if (StringUtils.isEmoji(content.charAt(index - 1)))
                --index;
            actContent = content.substring(0, --index);
            contentWidth = paint.measureText(actContent);
        }

        if (ellipse && actContent.length() >= 2 && actContent.length() < content.length()) {
            res = StringUtils.ellipse(actContent, maxWidth, paint);
        } else {
            res[0] = actContent;
            res[1] = contentWidth;
        }
        return res;
    }
}
